package com.globaldom.web.sales;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.globaldom.model.Deployment;
import com.globaldom.utils.MemCacheManager;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/market")
public class MarketController {
	public MarketController() {
	}

	// initializing method
	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(Model model, HttpSession session,HttpServletRequest request) {
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			return "loggedout";
			}
			
		Map<Integer, Long> deployedRes;

		PersistenceManager pmf = PMF.get().getPersistenceManager();
		try {
			deployedRes = MemCacheManager.getFreeResources(personID);
			if (null == deployedRes) {
				deployedRes = new HashMap<Integer, Long>();
//Get all the deployed resources
				Query query = pmf.newQuery( "Select ResourceType,sum(AvailResources) from " + Deployment.class.getName() + " where person==pid group by ResourceType");
				query.declareParameters("String pid");
				List<Deployment> deployment = (List<Deployment>) query.execute(personID);

				for (Iterator<Deployment> iterator = deployment.iterator(); iterator.hasNext();) {
					Deployment engDep = (Deployment) iterator.next();
					deployedRes.put(engDep.getResourceType(), engDep.getAvailResources());
				}

				
				MemCacheManager.putFreeResources(personID, deployedRes);
			}

			model.addAttribute("freeResources", deployedRes);
		} catch (Exception ex) {
			ex.printStackTrace();

		} finally {
			pmf.close();
		}
		return "market";
	}
}
